package com.xrkj.b2c.controller.sys;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.bcel.generic.IXOR;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import sun.print.SunPageSelection;

import com.sun.tools.classfile.StackMapTable_attribute.verification_type_info;
import com.xrkj.b2c.controller.common.BasicController;
import com.xrkj.b2c.dao.sys.SysRolePrivilegeMapper;
import com.xrkj.b2c.model.sys.SysPrivilege;
import com.xrkj.b2c.model.sys.SysRole;
import com.xrkj.b2c.model.sys.SysRolePrivilege;
import com.xrkj.b2c.service.sys.SysPrivilegeService;
import com.xrkj.b2c.service.sys.SysRoleService;
import com.xrkj.b2c.utils.StringUtil;
import com.xrkj.b2c.utils.UUIDUtil;
/**
 * 角色管理控制器类
 * @author 赵子靖
 *
 */
@RequestMapping("/sysRole")
@Controller
public class SysRoleController extends BasicController{
    
    @Autowired
    private SysRoleService roleService;
    @Autowired
    private SysPrivilegeService privilegeService;
    @Autowired
    private SysRolePrivilegeMapper rolePrivilegeDao;

    private Logger logger = Logger.getLogger(SysRoleController.class);

    /**
     * 
     * <B>方法名称：</B>转向管理页面<BR>
     * <B>概要说明：</B><BR>
     * 
     * @author Tom
     * @since 2017年10月9日
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("/forwardRole")
    public ModelAndView forwardRole(HttpServletRequest request, HttpServletResponse response) {
        String is = request.getParameter("t");
        request.setAttribute("is", is);
        return new ModelAndView("WEB-INF/pages/sys/sys-role/role-to-manager");
    }

    /**
     * 
     * <B>方法名称：</B>获取列表<BR>
     * <B>概要说明：</B><BR>
     * 
     * @author perry
     * @since 2017年10月20日
     * @param request
     * @param response
     * @param pageSize
     * @param pageNo
     * @return
     */
    @RequestMapping("/roleList")
    @ResponseBody
    public Object roleList(HttpServletRequest request, HttpServletResponse response) {
        String search = request.getParameter("search");//名称
        String offset = request.getParameter("offset");
        String limit = request.getParameter("limit");
        Map<String, Object> ret = new HashMap<String, Object>();
        Map<String, Object> paramter = new HashMap<String, Object>();
        paramter.put("offset", StringUtil.isEmpty(offset) ? null : Integer.parseInt(offset));
        paramter.put("limit", StringUtil.isEmpty(limit) ? null : Integer.parseInt(limit));
        paramter.put("search", search);
        paramter.put("pParentId", "root");
        Integer total = roleService.findRoleTotal(paramter);
        List<SysRole> roles = new ArrayList<SysRole>();
        if (total > 0) {
            roles = roleService.findRoleList(paramter);
        }
        ret.put("total", total);
        ret.put("rows", roles);
        return ret;
    }

    /**
     * 
     * <B>方法名称：</B>转向新增方法<BR>
     * <B>概要说明：</B><BR>
     * 
     * @author perry
     * @since 2017年10月20日
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("/forwardAddRole")
    public ModelAndView forwardAddRole(HttpServletRequest request, HttpServletResponse response) {
        //查询权限
        Map<String, Object> paramter = new HashMap<String, Object>();
        paramter.put("pParentId", "root");
        List<SysPrivilege> privileges = privilegeService.findPrivilegeList(paramter);
        if(privileges!=null && privileges.size()>0){
            for (SysPrivilege sysPrivilege : privileges) {
                Map<String, Object> subParamter = new HashMap<String, Object>();
                subParamter.put("pParentId", sysPrivilege.getpId());
                sysPrivilege.setSunPrivileges(privilegeService.findPrivilegeList(subParamter));
            }
        }
        request.setAttribute("privileges", privileges);
        return new ModelAndView("WEB-INF/pages/sys/sys-role/add-role-dialog");
    }

    /**
     * 
     * <B>方法名称：</B>新增<BR>
     * <B>概要说明：</B><BR>
     * 
     * @author perry
     * @since 2017年11月6日
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("/addRole")
    @ResponseBody
    public Map<String, Object> addRole(HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> ret = new HashMap<String, Object>();
        String rName = request.getParameter("rName");
        String rDesc = request.getParameter("rDesc");
        String rStatus = request.getParameter("rStatus");
        String privileges = request.getParameter("privileges");

        if (StringUtil.isEmpty(rName)) {
            ret.put("success", false);
            ret.put("msg", "保存失败，请输入角色名称");
            return ret;
        }
        SysRole role = new SysRole();
        role.setrId(UUIDUtil.id());
        role.setrName(rName);
        role.setrDesc(rDesc);
        role.setrStatus(StringUtil.isEmpty(rStatus) ? 0 : Integer.parseInt(rStatus));
        if ((roleService.insertRole(role) > 0)) {
            if(!StringUtil.isEmpty(privileges)){
                String[] privlegeArray = privileges.split(",");
                if(privlegeArray!=null && privlegeArray.length>0){
                    for(int i=0;i<privlegeArray.length;i++){
                        //关联权限
                        SysRolePrivilege rolePrivilege = new SysRolePrivilege();
                        rolePrivilege.setRpId(UUIDUtil.id());
                        rolePrivilege.setrId(role.getrId());
                        rolePrivilege.setpId(privlegeArray[i]);
                        rolePrivilegeDao.insert(rolePrivilege);
                    }
                }
            }
            ret.put("success", true);
            ret.put("msg", "保存成功。");
        } else {
            ret.put("success", false);
            ret.put("msg", "保存失败。");
        }
        return ret;
    }

    /**
     * 
     * <B>方法名称：</B>跳转修改页面<BR>
     * <B>概要说明：</B><BR>
     * 
     * @author perry
     * @since 2017年11月6日
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("/forwardUpdateRole")
    public ModelAndView forwardUpdateRole(HttpServletRequest request, HttpServletResponse response) {
        String id = request.getParameter("id");//编号
        SysRole role = roleService.selectByPrimaryKey(id);
        if(role!=null){
            //查询权限
            Map<String, Object> paramter = new HashMap<String, Object>();
            paramter.put("pParentId", "root");
            List<SysPrivilege> privileges = privilegeService.findPrivilegeList(paramter);
            if(privileges!=null && privileges.size()>0){
                for (SysPrivilege sysPrivilege : privileges) {
                    Map<String, Object> subParamter = new HashMap<String, Object>();
                    subParamter.put("pParentId", sysPrivilege.getpId());
                    sysPrivilege.setSunPrivileges(privilegeService.findPrivilegeList(subParamter));
                }
            }
            request.setAttribute("privileges", privileges);
        }
        request.setAttribute("item", role);
        return new ModelAndView("WEB-INF/pages/sys/sys-role/update-role-dialog");
    }

    /**
     * 
     * <B>方法名称：</B>根据ID获取信息<BR>
     * <B>概要说明：</B><BR>
     * 
     * @author perry
     * @since 2017年11月8日
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("/getRoleById")
    @ResponseBody
    public Map<String, Object> getRoleById(HttpServletRequest request, HttpServletResponse response) {
        String id = request.getParameter("id");//编号
        SysRole role = roleService.selectByPrimaryKey(id);
        Map<String, Object> ret = new HashMap<String, Object>();
        ret.put("item", role);
        return ret;
    }

    /**
     * 
     * <B>方法名称：</B>新增<BR>
     * <B>概要说明：</B><BR>
     * 
     * @author perry
     * @since 2017年11月6日
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("/updateRole")
    @ResponseBody
    public Map<String, Object> updateRole(HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> ret = new HashMap<String, Object>();
        String rId = request.getParameter("rId");
        String rName = request.getParameter("rName");
        String rDesc = request.getParameter("rDesc");
        String rStatus = request.getParameter("rStatus");
        String privileges = request.getParameter("privileges");

        if (StringUtil.isEmpty(rName)) {
            ret.put("success", false);
            ret.put("msg", "保存失败，请输入角色名称");
            return ret;
        }

        SysRole role = roleService.selectByPrimaryKey(rId);
        if (role == null) {
            ret.put("success", false);
            ret.put("msg", "保存失败，未获取到修改对象。");
            return ret;
        }
        role.setrName(rName);
        role.setrDesc(rDesc);
        role.setrStatus(StringUtil.isEmpty(rStatus) ? 0 : Integer.parseInt(rStatus));
        
        if ((roleService.update(role)) > 0) {
            
            if(!StringUtil.isEmpty(privileges)){
                //删除权限角色
                rolePrivilegeDao.deleteByPrimaryRoleId(role.getrId());
                //新增权限角色
                String[] privlegeArray = privileges.split(",");
                if(privlegeArray!=null && privlegeArray.length>0){
                    for(int i=0;i<privlegeArray.length;i++){
                        //关联权限
                        SysRolePrivilege rolePrivilege = new SysRolePrivilege();
                        rolePrivilege.setRpId(UUIDUtil.id());
                        rolePrivilege.setrId(role.getrId());
                        rolePrivilege.setpId(privlegeArray[i]);
                        rolePrivilegeDao.insert(rolePrivilege);
                    }
                }
            }
            ret.put("success", true);
            ret.put("msg", "保存成功。");
        } else {
            ret.put("success", false);
            ret.put("msg", "保存失败。");
        }
        return ret;
    }

    /**
     * 
     * <B>方法名称：</B>删除<BR>
     * <B>概要说明：</B><BR>
     * 
     * @author Tom
     * @since 2017年10月11日
     * @return
     */
    @RequestMapping("/deleteRole")
    @ResponseBody
    public Map<String, Object> deleteRole(HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> ret = new HashMap<String, Object>();
        String id = request.getParameter("id");
        if (roleService.deleteRole(id) > 0) {
            //删除成功
            ret.put("success", true);
            ret.put("msg", "删除成功。");
        } else {
            //删除失败
            ret.put("success", false);
            ret.put("msg", "删除失败");
        }
        return ret;
    }
    
    /**
     * 
     * <B>方法名称：</B>获取角色下的权限<BR>
     * <B>概要说明：</B><BR>
     * @author perry
     * @since 2017年12月5日 	
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("/getPrivilegesByRole")
    @ResponseBody
    public Map<String, Object> getPrivilegesByRole(HttpServletRequest request, HttpServletResponse response) {
        String id = request.getParameter("id");//编号
        SysRole role = roleService.selectByPrimaryKey(id);
        Map<String, Object> paramter = new HashMap<String, Object>();
        paramter.put("rId", id);
        List<SysRolePrivilege> rolePrivileges = rolePrivilegeDao.findRolePrivilegeList(paramter);
        Map<String, Object> ret = new HashMap<String, Object>();
        ret.put("rows", rolePrivileges);
        return ret;
    }
    
}
